<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayableMainlandVehicleModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MainlandVehicle extends Controller
{
    /**
     * 内地车辆列表
     */
    public function list(Request $request)
    {
        $pickup_date_start = $request->input('pickup_date_start', '');
        $pickup_date_end = $request->input('pickup_date_end', '');
        $delivery_date_start = $request->input('delivery_date_start', '');
        $delivery_date_end = $request->input('delivery_date_end', '');
        $pickup_address = $request->input('pickup_address', '');
        $delivery_address = $request->input('delivery_address', '');
        $agent_id = $request->input('agent_id', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableMainlandVehicleModel::with(['createAdmin', 'agent']);

        if ($pickup_date_start && $pickup_date_end) {
            $query->whereBetween('pickup_date', [$pickup_date_start, $pickup_date_end]);
        }

        if ($delivery_date_start && $delivery_date_end) {
            $query->whereBetween('delivery_date', [$delivery_date_start, $delivery_date_end]);
        }

        if ($pickup_address) {
            $query->where('pickup_address', 'like', "%{$pickup_address}%");
        }

        if ($delivery_address) {
            $query->where('delivery_address', 'like', "%{$delivery_address}%");
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'pickup_date' => $item->pickup_date,
                    'delivery_date' => $item->delivery_date,
                    'pickup_address' => $item->pickup_address,
                    'delivery_address' => $item->delivery_address,
                    'quantity' => $item->quantity,
                    'volume' => $item->volume,
                    'weight' => $item->weight,
                    'unit_price' => $item->unit_price,
                    'freight' => $item->freight,
                    'tax_freight' => $item->tax_freight,
                    'remarks' => $item->remarks,
                    'status' => $item->status,
                    'status_name' => PayableMainlandVehicleModel::STATUS_LIST[$item->status] ?? '',
                    'pay_amount' => $item->pay_amount,
                    'created_admin_id' => $item->created_admin_id,
                    'created_admin_name' => $item->createAdmin->name ?? '',
                    'created_at' => $item->created_at->format('Y-m-d H:i:s')
                ];
            });


        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加内地车辆记录
     */
    public function add(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'agent_id' => 'required|integer|min:1',
            'pickup_date' => 'required|date',
            'delivery_date' => 'required|date',
            'pickup_address' => 'required|string',
            'delivery_address' => 'required|string',
            'quantity' => 'required|integer|min:0',
            'volume' => 'required|numeric|min:0',
            'weight' => 'required|numeric|min:0',
            'unit_price' => 'required|numeric|min:0',
            'freight' => 'required|numeric|min:0',
            'tax_freight' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        try {
            $vehicle = new PayableMainlandVehicleModel();
            $vehicle->agent_id = $params['agent_id'];
            $vehicle->pickup_date = $params['pickup_date'];
            $vehicle->delivery_date = $params['delivery_date'];
            $vehicle->pickup_address = $params['pickup_address'];
            $vehicle->delivery_address = $params['delivery_address'];
            $vehicle->quantity = $params['quantity'];
            $vehicle->volume = $params['volume'];
            $vehicle->weight = $params['weight'];
            $vehicle->unit_price = $params['unit_price'];
            $vehicle->freight = $params['freight'];
            $vehicle->tax_freight = $params['tax_freight'];
            $vehicle->remarks = $params['remarks'] ?? '';
            $vehicle->status = PayableMainlandVehicleModel::STATUS_UNPAID;
            $vehicle->pay_amount = 0;
            $vehicle->created_admin_id = $request->get('auth')->id;
            $vehicle->save();

            return $this->success($vehicle);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新内地车辆记录
     */
    public function update(Request $request, $id)
    {
        $vehicle = PayableMainlandVehicleModel::find($id);
        if (!$vehicle) {
            return $this->error('内地车辆记录不存在');
        }

        $params = $request->all();
        $validator = Validator::make($params, [
            'agent_id' => 'required|integer|min:1',
            'pickup_date' => 'required|date',
            'delivery_date' => 'required|date',
            'pickup_address' => 'required|string',
            'delivery_address' => 'required|string',
            'quantity' => 'required|integer|min:0',
            'volume' => 'required|numeric|min:0',
            'weight' => 'required|numeric|min:0',
            'unit_price' => 'required|numeric|min:0',
            'freight' => 'required|numeric|min:0',
            'tax_freight' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        try {
            $vehicle->agent_id = $params['agent_id'];
            $vehicle->pickup_date = $params['pickup_date'];
            $vehicle->delivery_date = $params['delivery_date'];
            $vehicle->pickup_address = $params['pickup_address'];
            $vehicle->delivery_address = $params['delivery_address'];
            $vehicle->quantity = $params['quantity'];
            $vehicle->volume = $params['volume'];
            $vehicle->weight = $params['weight'];
            $vehicle->unit_price = $params['unit_price'];
            $vehicle->freight = $params['freight'];
            $vehicle->tax_freight = $params['tax_freight'];
            $vehicle->remarks = $params['remarks'] ?? '';
            $vehicle->save();

            return $this->success($vehicle);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除内地车辆记录
     */
    public function delete($id)
    {
        $vehicle = PayableMainlandVehicleModel::find($id);
        if (!$vehicle) {
            return $this->error('内地车辆记录不存在');
        }

        if ($vehicle->status != PayableMainlandVehicleModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $vehicle->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取内地车辆详情
     */
    public function detail($id)
    {
        $vehicle = PayableMainlandVehicleModel::with(['createAdmin', 'agent'])->find($id);
        if (!$vehicle) {
            return $this->error('内地车辆记录不存在');
        }

        $data = $vehicle->toArray();
        $data['agent_name'] = $vehicle->agent->name ?? '';
        $data['status_name'] = PayableMainlandVehicleModel::STATUS_LIST[$vehicle->status] ?? '';
        $data['created_admin_name'] = $vehicle->createAdmin->name ?? '';

        return $this->success($data);
    }

    /**
     * 设置付款状态
     */
    public function setPaid(Request $request, $id)
    {
        $vehicle = PayableMainlandVehicleModel::find($id);
        if (!$vehicle) {
            return $this->error('内地车辆记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'pay_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $payAmount = $request->input('pay_amount');
        $totalAmount = $vehicle->freight;

        // 设置付款状态
        if ($payAmount >= $totalAmount) {
            $status = PayableMainlandVehicleModel::STATUS_PAID;
            $payAmount = $totalAmount; // 确保支付金额不超过总金额
        } elseif ($payAmount > 0) {
            $status = PayableMainlandVehicleModel::STATUS_PART_PAID;
        } else {
            $status = PayableMainlandVehicleModel::STATUS_UNPAID;
        }

        try {
            $vehicle->pay_amount = $payAmount;
            $vehicle->status = $status;
            $vehicle->save();

            return $this->success($vehicle);
        } catch (\Exception $e) {
            return $this->error('设置付款状态失败：' . $e->getMessage());
        }
    }
} 